/*
 * @Author: malgee
 * @Date: 2025-04-17 11:28:15
 * @LastEditors: maling
 * @LastEditTime: 2025-04-27 13:20:52
 * @FilePath: /vue3-ts-cms/src/router/index.ts
 * @Description: 
 * 
 */
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import localStorageCache from '@/utils/cache'
import { firstMenu } from '@/utils/map-menus'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'main',
    redirect: '/main',
  },
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "login" */ '@/views/login/login.vue')
  },
  {
    path: '/main',
    name: 'main',
    component: () => import(/* webpackChunkName: "main" */ '@/views/main/main.vue')
     // children: [] -> 根据userMenus来决定 -> children , 动态设置
  },
  {
    path: '/:pathMatch(.*)',
    name: 'not-found',
    component: () => import(/* webpackChunkName: "not-found" */ '@/views/not-found/not-found.vue')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 导航守卫
router.beforeEach((to, from, next) => {
  // 非登录页如果没有带 token，重定向到登录页
  if (to.name !== 'login') {
    const token = localStorageCache.get('token')
    if (!token) {
      next('/login')
    }   
  } 

  if (to.name === '/main') {
    return firstMenu.url
  }
  next() 
})


export default router
